/**
 * Capacitance sensor module. It cooperates with the LKN sensor board module call SBoardC.
 * It recalculates value read from ADC into value of capacitance. It provides interface Read<double>.
 *
 * @author Paweł Pawłowski <abdul-pablo@tlen.pl>
 * @author Leily Zafari
 **/

#include<math.h>
#include "capacitance.h"

module CapacitanceSensorM {
	provides {
		interface Read<double>;
	}
	uses {
		interface SBoard;
	}
}

implementation {
	double sensorValue;
	double capacitanceValue;
	error_t sensorResult;
	double vref = C_SENSOR_VREF_VALUE;

	task void readDoneTask();

	/**
	 * @brief This command delegates the sensor read call to sensor board A/D converter.
	 *
	 * @return error_t Status of command invocation.
	 */
	command error_t Read.read()
	{
		call SBoard.readChannel2();
		return SUCCESS;
	}

	/**
	 * @brief Event signaled after reading from A/D converter.
	 * @details If the read value corresponds to appropriate channel,
	 * it is saved and readDoneTask is posted.
	 *
	 * @see readDoneTask()
	 *
	 * @param channel uint8_t Number of analog channel that was sampled by the A/D converter
	 * @param value uint8_t Value return by the ADC with respect to reference voltage
	 * @return void
	 */
	async event void SBoard.readDoneADC(uint8_t channel, double value){
		//post data processing task
		if(channel == 2)
		{
			sensorValue = value;
			sensorResult = SUCCESS;
			post readDoneTask();
		}
	}

	/**
	 * Event signaled after reading from SBoard IO port
	 *
	 * @param value uint8_t Value of IO port return by SBoard component
	 * @return void
	 */
	async event void SBoard.readDoneIO(uint8_t){

	}

	/**
	 * @brief Task processing sensor data and signaling readDone event.
	 *
	 * @return void
	 */
  	task void readDoneTask()
  	{
  		//these recalculation are not based on any physical properties of the measurement circuit
  		//for our purpose only a threshold value is to be determined
		capacitanceValue = ((double)sensorValue/(double)vref)*1000;
		capacitanceValue = 1/capacitanceValue;
 		signal Read.readDone(sensorResult, capacitanceValue*1000);
  	}
}